<template>
    <view class="tocard-info" v-if="!webviewSrc">
        <view class="tocard-line tocard-border">
            <!-- todo:获取银行卡信息接口 -->
            <view class="tocard-label">提现至</view>
            <view class="tocard-type" v-if="bankName">{{ bankName }}（{{ bankAccountNoTail }}）</view>
            <view class="tocard-type" v-else>
                <!-- 未绑定银行卡 -->
            </view>
        </view>
        <view class="tocard-money">
            <view class="tocard-label tocard-content">提现金额(元)</view>
            <!-- todo:提现至余额大小限制接口 -->
            <input
                v-model="money"
                type="digit"
                placeholder="请输入提现金额"
                :placeholder-style="'color: #cccc;' + 'font-size:36rpx'"
                @input="handleInput" />
        </view>
        <!-- todo:显示余额样式  todo:余额接口-->
        <view class="balance-tip-box" v-if="isTipError">
            <view class="balance-tip">{{ isTipError }}</view>
        </view>
        <view class="balance-tip-box" v-else>
            <view class="balance-tip" v-if="balanceVisible">
                <template v-if="balanceIsNull">
                    <!-- *获取余额失败，请稍后重试 -->
                </template>
                <template v-else> *提现金额不得超过￥{{ balance }} </template>
            </view>
        </view>
        <view class="tocard-btn">
            <!-- todo:判断委托授权 -->
            <view class="tocard-alert" v-if="isEntrustNotAuthorization" @tap="handleAuthorization">
                <image :src="getImgOssUrl('/ui-prod-2.11.0/error.png')" class="tocard-image"></image>
                <span>请先授权委托提现</span>
            </view>
            <view class="tocard-alert tocard-choose" v-if="isNotEntrustAuthorization">
                <image :src="getImgOssUrl('/ui-prod-2.11.0/paysucess.png')" class="tocard-image"></image>
                <span>已授权委托提现</span>
            </view>
            <view class="tocard-click" v-if="!withdrawalDisabled" @tap="handleWithdrawal">申请提现</view>
            <view class="tocard-disabled" v-else>申请提现</view>
        </view>
        <!-- <u-keyboard
            ref="uKeyboard"
            tips="输入密码"
            mode="number"
            :show="keyboardShow"
            :safeAreaInsetBottom="true"
            :dotDisabled="false"
            :focus="false"
            @backspace="handleBackspace"
            @change="handleChange"
            @close="handleClose"
            @cancel="handleCancel"
            @confirm="handleConfirm">
            <u-code-input
                class="custom-code-input"
                :disabledKeyboard="true"
                :value="keyPassword"
                :maxlength="6"
                :dot="true"></u-code-input>
        </u-keyboard> -->
        <uni-popup ref="passwordPopupRef" :mask-click="false">
            <view class="password-popup">
                <view class="password-popup-tip">绑卡成功，请设置支付密码</view>
                <view class="password-last"><view class="password-btn" @tap="handleRoutePwd"> 立即设置 </view></view>
            </view>
        </uni-popup>
    </view>
    <!-- webview承载密码设置页和宝付通授权页 -->
    <web-view v-if="webviewSrc" :src="webviewSrc" ref="webview" class="webview" @message="handlePostMessage"></web-view>
</template>
<script setup>
import { ref, computed, nextTick } from 'vue';
import { onShow, onHide } from '@dcloudio/uni-app';
import request from '@/request';
import { getImgOssUrl } from '@/commons/utils';
import { debounce } from 'lodash';
import router from '@/router';

/* -------------------------------- 输入框输入start -------------------------------- */
let money = ref(null);
let balance = ref(null);
let isTipError = ref('');
const isMoneyAllow = computed(() => {
    // 不能为空或者0
    if (!money.value || /^0(\.?0+)?$/.test(money.value)) {
        return false;
    }
    // 必须是正确的数字
    if (!/^\d+(\.\d+)?$/.test(money.value)) {
        return false;
    }
    // 必须是两位小数
    if (!/^(\d+)(.\d{0,2})?$/.test(money.value)) {
        return false;
    }
    return true;
});
const balanceDisabled = computed(() => {
    // 输入金额是否大于余额
    return (money.value || 0) / 1 > (balance.value || 0) / 1;
});
const balanceIsNull = computed(() => {
    // 余额是否空
    return [null, undefined].includes(balance.value);
});
const balanceVisible = computed(() => {
    // 余额提示信息显示
    if (!isMoneyAllow.value) {
        return false;
    }
    // if (balanceIsNull.value) {
    //     return false;
    // }
    return balanceDisabled.value;
});
const handleInput = debounce(async () => {
    // 键盘输入
    // 提现金额：纯数字，＞0，≤账户余额，最多2位小数；
    // 用户输入0，则按钮淡色，不可点击
    // 用户输入＞0的数字后，就要立即调接口，是否超过最新的可用余额
    // 若是，则提示“提现金额不得超过￥20.09”
    if (!money.value || /^0(\.?0+)?$/.test(money.value)) {
        isTipError.value = /^0(\.?0+)?$/.test(money.value) ? '*请输入大于0的数字' : '';
        return;
    }
    if (!/^\d+(\.\d+)?$/.test(money.value)) {
        isTipError.value = '*请输入正确的数字';
        return;
    }
    if (!/^(\d+)(.\d{0,2})?$/.test(money.value)) {
        isTipError.value = '*提现金额最多为两位小数';
        return;
    }
    isTipError.value = '';
    // 输入调取余额接口
    const { data } = await request('walletBalance');
    balance.value = ((data || {})?.balance || 0) / 100;
}, 500);
/* -------------------------------- 输入框输入end -------------------------------- */

/* -------------------------------- 调起提现密码键盘start -------------------------------- */
let keyboardShow = ref(false);
let keyPassword = ref('');
const handleWithdrawal = debounce(async () => {
    // 提现调取密码接口
    // if (isEntrust.value) {
    //     keyPassword.value = '';
    //     keyboardShow.value = true;
    //     return;
    // }
    // 提现成功跳转成功页面
    uni.showLoading({
        title: '提现中...',
        mask: true
    });
    await request('withdrawToWechat', {
        withdrawMethod: 2, //提现至: 1-微信 2-银行卡
        amount: money.value * 100, //提现金额（单位：分，未除100）
        bankCardId: bankCardId.value, //用户绑定的银行卡ID
        password: '' //提现密码
    });
    // 跳转至成功页
    router.redirectTo({
        url: '/pages-user/balanceCash/cash/cashStatus'
    });
}, 500);

let bankName = ref('');
let bankAccountNoTail = ref('');
let bankCardId = ref('');
const handleConfirm = async () => {
    // 提现成功跳转成功页面
    uni.showLoading({
        title: '提现中...',
        mask: true
    });
    await request('withdrawToWechat', {
        withdrawMethod: 2, //提现至: 1-微信 2-银行卡
        amount: money.value * 100, //提现金额（单位：分，未除100）
        bankCardId: bankCardId.value, //用户绑定的银行卡ID
        password: keyPassword.value //提现密码
    });

    handleCancel();
    // 跳转至成功页
    router.redirectTo({
        url: '/pages-user/balanceCash/cash/cashStatus'
    });
};

const handleClose = () => {
    // 关闭键盘keyPassword置空
    // keyPassword.value = '';
};
const handleBackspace = () => {
    // 删除密码
    if (keyPassword.value > 0) {
        keyPassword.value = keyPassword.value.substring(0, keyPassword.value.length - 1);
    }
};
const handleCancel = () => {
    // 取消键盘
    keyboardShow.value = false;
};
const handleChange = val => {
    // 密码改变
    if (keyPassword.value.length < 6) {
        keyPassword.value += val;
    }
    if (keyPassword.value.length >= 6) {
        return;
    }
};
/* -------------------------------- 调起提现密码键盘end -------------------------------- */

/* -------------------------------- 提现按钮是否能点击start -------------------------------- */
let isAuthorization = ref(false);
const hasAuthorization = async () => {
    // todo:委托提现授权
    const { data } = await request('authorizationEnable');
    isAuthorization.value = data?.enable;
};
const handleAuthorization = async () => {
    // 两种方式
    // 1.跳转授权页
    router.push({
        path: '/pages-user/balanceCash/cash/cardWebview',
        query: {
            type: 'authorization'
        }
    });
    // 2.当前页面webview
    // const { data } = await request('authorizationUrl', {
    //     callType: 'SIGN_WITHDRAW_ENTRUST'
    // });
    // webviewSrc.value = data?.redirectUrl;
};

let isEntrust = ref(false);
const isEntrustNotAuthorization = computed(() => {
    // 已委托但未授权提现
    return isEntrust.value && !isAuthorization.value;
});
const isNotEntrustAuthorization = computed(() => {
    // 已委托但未授权提现
    return isEntrust.value && isAuthorization.value;
});
const withdrawalDisabled = computed(() => {
    // 按钮禁用态
    return !bankName.value || !isMoneyAllow.value || balanceDisabled.value || isEntrustNotAuthorization.value;
});
const hasEntrust = async () => {
    // todo:是否委托扣款
    const { data } = await request('autoDeduct');
    isEntrust.value = data?.deduct;
};
let isPassword = ref(false);
let passwordPopupRef = ref();
const hasPassword = async () => {
    // 是否设置密码
    const { data } = await request('payPassword');
    isPassword.value = data?.setted;
    if (!isPassword.value) {
        passwordPopupRef.value.open('center');
        // 如果没有设置密码，弹窗提示设置密码
        // uni.showModal({
        //     title: '绑卡成功，请设置支付密码',
        //     icon: 'none',
        //     showCancel: false,
        //     confirmText: '立即设置',
        //     success: async () => {
        //         // 两种方式
        //         // 1.跳转设置密码页面
        //         router.push({
        //             path: '/pages-user/balanceCash/cash/cardWebview',
        //             query: {
        //                 type: 'password'
        //             }
        //         });
        //         // 2.当前页面webview
        //         // const { data } = await request('passwordUrl');
        //         // webviewSrc.value = data?.redirectUrl;
        //         // https://account.baofoo.com/front/v3/#/paid_pass/727f4301a7854f1fbc6e63623430e318?Address=商户需要返回的指定页面路径
        //     }
        // });
    } else {
        passwordPopupRef?.value?.close();
    }
};
const handleRoutePwd = () => {
    router.push({
        path: '/pages-user/balanceCash/cash/cardWebview',
        query: {
            type: 'password'
        }
    });
};
/* -------------------------------- 提现按钮是否能点击end -------------------------------- */

// webview
const webviewRef = ref();
let webviewSrc = ref();
const handlePostMessage = event => {
    // 监听webview消息通知
    // event.detail.data
    webviewSrc.value = '';
    webviewRef?.value?.bfCloseH5();
};

// 获取银行卡信息
const getBankInfo = async () => {
    try {
        const { data } = await request('walletCheckBankCard');
        bankName.value = data?.bankName;
        bankAccountNoTail.value = data?.bankAccountNoTail;
        bankCardId.value = data?.bankCardId;
    } catch (err) {
        uni.showToast({
            title: err?.data?.msg,
            icon: 'none'
        });
    }
};

onShow(async () => {
    webviewSrc.value = '';
    await getBankInfo();
    if (!bankName.value) {
        // 没有配置银行卡，就中断下边的判断
        return;
    }
    await hasEntrust();
    // 是否委托，且未设置密码和授权
    if (isEntrust.value) {
        if (!isAuthorization.value) {
            // 未授权发起授权校验
            hasAuthorization();
        }
        if (!isPassword?.value) {
            // 未获取密码发送密码验证请求
            hasPassword();
        }
    }
});
</script>
<style lang="scss" scoped src="./style/tocard.scss"></style>
